package com.example.client.listen;

import cn.hutool.json.JSONUtil;
import com.example.client.dto.ResultDTO;
import jakarta.websocket.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.ByteBuffer;

@ClientEndpoint
@Component
@Slf4j
public class WebSocketClientEndpoint {

    private Session userSession;

    @OnOpen
    public void onOpen(Session session) {
        this.userSession = session;
        log.info("连接成功 session：{}",session.getId());
    }

    @OnMessage
    public void onMessage(String message, Session session) throws IOException {
        // 处理从WebSocket服务器接收到的消息
        log.info("Received text message from server: " + message);
        ResultDTO resultDTO = JSONUtil.toBean(message, ResultDTO.class);
        String action = resultDTO.getAction();
        if("speech_end".equals(action)){
            log.info("本次会话结束 session：{}",session.getId());
            session.close();
        }
    }

    @OnMessage
    public void onMessage(byte[] message, Session session) {
        // 处理从WebSocket服务器接收到的消息
        log.info("Received byte message from server: " + message.length);
    }

    @OnClose
    public void onClose(Session session, CloseReason closeReason) {
        this.userSession = null;
    }

    public void sendByteMessage(Session session,byte[] message) throws IOException {
        session.getBasicRemote().sendBinary(ByteBuffer.wrap(message));
    }

    public void sendTextMessage(Session session,String message) throws IOException {
        session.getBasicRemote().sendText(message);
    }

//    public static void main(String[] args) {
//        try {
//            // 创建WebSocket客户端
//            WebSocketContainer container = ContainerProvider.getWebSocketContainer();
//            String uri = "ws://127.0.0.1:8080/websocket/123"; // 请替换为实际的WebSocket服务器URI
//            container.connectToServer(WebSocketClientEndpoint.class, URI.create(uri));
//            // 上传文件并发送到WebSocket服务器
//            Path filePath = Path.of("/Users/zhouhailong/Documents/请求流程（协同）.jpg"); // 请替换为实际的文件路径
//            byte[] fileBytes = Files.readAllBytes(filePath);
//            int chunkSize = 1024 * 6;
//            for (int i = 0; i < fileBytes.length; i += chunkSize) {
//                int endIndex = Math.min(i + chunkSize, fileBytes.length);
//                byte[] chunk = new byte[endIndex - i];
//                System.arraycopy(fileBytes, i, chunk, 0, chunk.length);
//                // 使用WebSocket客户端发送文件块
//                new WebSocketClientEndpoint().sendMessage(chunk);
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }
}
